#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "WangJing"
# Date: 2018/10/30

import time
from dingtalkchatbot.chatbot import DingtalkChatbot
from collections import Counter
from datetime import datetime, timedelta
import pandas as pd


from weater_rule import Rule
from hefeng import get_json,air_now_weater


class Expression_travel(Rule):
    def __init__(self,set_weater,air_now,air_flag,data_now):
        super(Expression_travel,self).__init__(set_weater,air_now,air_flag,data_now)

        self.text =''
        self.rain_day= {1:'明天',2:'后天',3:'大后天'}
        self.air_flag = air_flag
        self.air_now = air_now
        self.data_now = data_now

    ############1.是否下雨###################
    def rain_travel(self):
        ###目的地天气规则
        ###是否下雨

        rain_data = self.rain()
        ts_weater =self.specical_weater()

        if len(rain_data):
            ts = self.set_weater.loc[int(rain_data.index[0])]
            if int(ts['cond_code_d']) == int(ts['cond_code_n']):
                weate_c = ts['weater']
            else:
                weate_l = ts['weater'].split('转')
                if '雨' in weate_l[0]:
                    weate_c = weate_l[0]
                else:
                    weate_c = weate_l[1]

        ##今天下雨
        if 0 in rain_data.index or False:
            self.text += '今日有{},记得携带雨具\n'.format(weate_c)

        #特殊天气
        elif len(ts_weater):
            self.text += '{}有{},注意安全\n'.format(ts_weater['time'][0],ts_weater['weater'][0])

        elif len(rain_data):
            ran_3 = list(filter(lambda x:x if x<4 else 0,list(rain_data.index)))

            ##三天持续下雨
            if len(ran_3) >= 3:
                self.text += '未来三天,持续降雨\n'

            ##三天内某天下雨
            elif int(rain_data.index[0]) in self.rain_day.keys():
                self.text += '{}有{},出门记得携带雨具\n'.format(self.rain_day[int(rain_data.index[0])],weate_c)

        ##未来三天的主要天气
        else:
            weater_d = self.set_weater['cond_code_d'][1:4].tolist()
            code_data = self.get_code()
            weater_txt_d = Counter(list(map(lambda x:code_data[code_data['Code'] == int(x)]['China'].tolist()[0],weater_d)))
            self.text += '未来三天{}'.format(weater_txt_d.most_common(1)[0][0])


     ############2、湿度#############
    def hum_weater(self):
        #湿度
        if int(self.set_weater['hum'][0]) <40:
            self.text += '天气干燥，多喝水\n'
        elif int(self.set_weater['hum'][0]) >85:
            self.text += '潮湿天气,少开门窗\n'

        if int(self.set_weater['wind_sc'][0].split('-')[1]) >= 6:
            self.text += '风力过大，注意安全\n'


    ##########3.温度变化#############
    def weater_cut(self):
        ##日均温差
        if int(self.set_weater['tmp_max'][0]) - int(self.set_weater['tmp_min'][0]) >=7:
            self.text += '日均温差较大\n'


    def weater_process(self):
        weater_data = self.weater_hight()
        weater = self.weater_comparison()
        wd_d_low = int(weater['flu_max'].min())
        wd_d_high = int(weater['flu_max'].max())
        wd_n_low = int(weater['flu_min'].min())
        wd_n_high = int(weater['flu_min'].max())

        #夏天天气
        if sum(weater_data['high_wd'][:3]) >= 3:
            self.text += '未来三天，将持续高温\n'

        ###通用大幅降温或者大幅升温
        elif  wd_d_low <= -5 or wd_n_low <= -5 :
            wd_d_day = weater[weater['flu_max'].astype(int)==wd_d_low].index.tolist()[0]
            wd_n_day  = weater[weater['flu_min'].astype(int) == wd_n_low].index.tolist()[0]
            if wd_d_low <=-5 and wd_n_low <= -5:
                low_day = min(wd_d_day,wd_n_day)
            elif wd_d_low < wd_n_low:
                low_day = wd_d_day
            else:
                low_day = wd_n_day

            if low_day+1 in self.rain_day.keys():
                self.text += '{}大幅降温,降至{}℃\n'.format(self.rain_day[low_day+1],self.set_weater.loc[low_day]['tmp_min'])

        elif wd_d_high >= 5 or wd_n_high >= 5:
            if wd_d_high > wd_n_high:
                max_day = weater[weater['flu_max'].astype(int) == wd_n_high].index.tolist()[0]
            else:
                max_day = weater[weater['flu_min'].astype(int) == wd_n_high].index.tolist()[0]

            if max_day+1 in self.rain_day.keys():
                self.text += '{}大幅升温,升至{}℃\n'.format(self.rain_day[max_day+1],self.set_weater.loc[max_day]['tmp_max'])
        print()

    #############4、紫外线强度##################
    def zwx(self):
        ##紫外线强度指数
        if int(self.data_now) < 18:#晚上无此数据
            if int(self.set_weater['uv_index'][0]) >=6:
                self.text += '今日紫外线强度较强,注意防晒\n'
        else:
            if int(self.set_weater['uv_index'][1]) >=6:
                self.text += '明日紫外线强度较强,注意防晒\n'

    ###########5、空气质量##################
    def air(self):
        if self.air_flag:
            if int(self.air_now['aqi']) >201:
                self.text += '今日空气重度污染，出门记得带口罩哦\n'
            elif int(self.air_now['aqi']) >150:
                self.text += '今日空气中度污染，出门记得带口罩哦\n'


    ##########6、能见度分析##################
    def vis(self):
        if int(self.set_weater['vis'][0]) <= 1:
            self.text += '能见度极差,仅{}公里,开车请小心'.format(self.set_weater['vis'][0])
        elif  int(self.set_weater['vis'][0]) < 10:
            self.text += '能见度{}公里,视野不清晰,开车请小心'.format(self.set_weater['vis'][0])



def ding(data):
    # WebHook地址
    webhook = 'https://oapi.dingtalk.com/robot/send?access_token=c023ebfff1eef6e24393f4f1d82c11a7a589edbcb10b56f4b7bbcf463091a67d'
    # 初始化机器人小丁
    xiaoding = DingtalkChatbot(webhook)
    # Text消息@所有人
    xiaoding.send_text(msg=data, is_at_all=None)


def main():
    city = 'sanya'#quanzhou  fuzhou  shenzhen  beijing   tianjin
    data_now = time.strftime('%H', time.localtime()) # 当前时间

    #获取数据
    set_weater = get_json(city)
    air_now = air_now_weater(city)
    #转变格式为dataframe
    if air_now:
        air_now_pd = pd.DataFrame([air_now])
        air_flag = True
    else:
        air_now_pd = air_now
        air_flag = False
    set_weater_pd = pd.DataFrame(set_weater)#.iloc[:4,:]


    expression_travel_dc = Expression_travel(set_weater_pd,air_now_pd,air_flag,data_now)
    expression_travel_dc.rain_travel()
    expression_travel_dc.hum_weater()
    expression_travel_dc.weater_cut()
    expression_travel_dc.weater_process()
    expression_travel_dc.zwx()
    expression_travel_dc.air()
    expression_travel_dc.vis()


    text = city
    text += '\n'
    text += expression_travel_dc.text
    print(text)
    print('完成一次气象更新')

    if False:
        ding(text)


if __name__ == '__main__':
    main()